﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using Catch.ISQLServerDAL;
using Catch.SQLServerDAL;
using System.Configuration;
using System.IO;
using System.Reflection;
using System.Xml;
using TongTech.TLQ62;

namespace ChachMessage
{
    public partial class CatchServer : ServiceBase
    {
        #region 配置信息
        /// <summary>
        /// 数据库类型
        /// </summary>
        private readonly string TypeName = "Catch.SQLServerDAL." + ConfigurationManager.AppSettings["SQLTYPE"];
        /// <summary>
        /// 默认值，不改变
        /// </summary>
        private readonly string Path = "Catch.SQLServerDAL";
        /// <summary>
        /// 保存文件路径
        /// </summary>
        private readonly string savepath = ConfigurationManager.AppSettings["SAVEPATH"].ToString();
        /// <summary>
        /// 根节点
        /// </summary>
        private readonly string root = ConfigurationManager.AppSettings["root"].ToString();
        /// <summary>
        /// 产品节点
        /// </summary>
        private readonly string product = ConfigurationManager.AppSettings["product"].ToString();
        /// <summary>
        /// 节点内容
        /// </summary>
        private readonly string[] node = ConfigurationManager.AppSettings["node"].ToString().Split(',');
        /// <summary>
        /// 多少秒执行一次
        /// </summary>
        private readonly int miao = int.Parse(ConfigurationManager.AppSettings["TICK"].ToString()) * 1000;
        /// <summary>
        /// 数据库执行语句 #DATE# 是执行时间，执行后替换成当前时间
        /// </summary>
        private readonly string configSQL = ConfigurationManager.AppSettings["SQL"].ToString();
        /// <summary>
        /// 多少条存一个文件
        /// </summary>
        private readonly int counts = int.Parse(ConfigurationManager.AppSettings["COUNTS"].ToString());
        /// <summary>
        /// 公司名称缩写
        /// </summary>
        private readonly string companyName = ConfigurationManager.AppSettings["COMPANYNAME"].ToString();
        /// <summary>
        /// 公司中文名称
        /// </summary>
        private readonly string chinaName = ConfigurationManager.AppSettings["CHINANAME"].ToString();
        /// <summary>
        /// 优先级
        /// </summary>
        private readonly byte PriorNo = byte.Parse(ConfigurationManager.AppSettings["PriorNo"].ToString());
        /// <summary>
        /// 队列名称
        /// </summary>
        private readonly string QueName = ConfigurationManager.AppSettings["QueName"].ToString();
        /// <summary>
        /// 程序编号
        /// </summary>
        private readonly int ProgramNO = int.Parse(ConfigurationManager.AppSettings["ProgramNO"].ToString());
        #endregion
        /// <summary>
        /// 服务构造函数
        /// </summary>
        public CatchServer()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 服务启动事件
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(string[] args)
        {

            try
            {
                if (!Directory.Exists(savepath))
                {
                    Directory.CreateDirectory(savepath);
                }

                MyTimer();
            }
            catch
            { }
        }
        //实例化System.Timers.Timer
        private void MyTimer()
        {
            System.Timers.Timer MT = new System.Timers.Timer(miao);
            MT.Elapsed += new System.Timers.ElapsedEventHandler(MTimedEvent);

            MT.Enabled = true;

        }
        /// <summary>
        /// 时钟事件
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void MTimedEvent(object source, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                string datetimestring = DateTime.Now.ToString();
                string olddatetimestring = ConfigurationManager.AppSettings["DATE"].ToString();
                string sqlstring = configSQL.Replace("#DATE#", olddatetimestring).Replace("#QYNAME#", chinaName);
                config.AppSettings.Settings["DATE"].Value = datetimestring;
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
                ISQLManager mger;
                mger = (ISQLManager)Assembly.Load(Path).CreateInstance(TypeName);//反射创建
                DataSet ds = mger.GetDateSet(sqlstring);
                if (ds.Tables != null && ds.Tables[0].Rows.Count > 0)
                {
                    XmlDocument xmldoc1 = new XmlDocument();
                    //加入XML的声明段落,<?xml version="1.0" encoding="gb2312"?>
                    XmlDeclaration xmldecl1;
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        if (i % counts == 0)
                        {
                            xmldoc1 = new XmlDocument();
                            xmldecl1 = xmldoc1.CreateXmlDeclaration("1.0", "gb2312", null);
                            xmldoc1.AppendChild(xmldecl1);
                            XmlElement xmlelem = xmldoc1.CreateElement("", root, "");
                            xmldoc1.AppendChild(xmlelem);
                        }

                        XmlNode baseroot = xmldoc1.SelectSingleNode(root);//查找<根节点> 
                        XmlElement xe1 = xmldoc1.CreateElement(product);//创建一个<产品>节点 
                        for (int j = 0; j < node.Length; j++)
                        {
                            XmlElement xesub1 = xmldoc1.CreateElement(node[j]);
                            if (ds.Tables[0].Columns.Count <= j)
                            {
                                xesub1.InnerText = "";
                            }
                            else
                            {
                                xesub1.InnerText = ds.Tables[0].Rows[i][j].ToString();
                            }
                            xe1.AppendChild(xesub1);

                            baseroot.AppendChild(xe1);//添加到<根>节点中 
                            if ((j + 1 == node.Length) && ((i + 1) % counts == 0 && i != 0) || ds.Tables[0].Rows.Count == i + 1)
                            {
                                //根据时间保存文件名
                                string filename = companyName + DateTime.Now.ToString().Replace(" ", "").Replace(":", "").Replace("-", "") + i.ToString() + ".xml";
                                xmldoc1.Save(savepath + filename);
                                SendFile(filename);
                            }
                        }
                    }
                }
            }
            catch
            { }
        }
        /// <summary>
        /// 发送文件
        /// </summary>
        /// <param name="filename"></param>
        private void SendFile(string filename)
        {
            TLQ_ID tlqId = new TLQ_ID();

            bool online = tlqInterface.tlq_login(ref tlqId, ProgramNO, 0) >= 0;
            if (online)
            {
                // string filename = textBox1.Text;// "readme.txt";
                TLQMSG_INFO msginfo = new TLQMSG_INFO();
                msginfo.CompressFlag = 0;//1压缩，0不压缩
                msginfo.Expiry = -1;//生命周期-1，为无限若Expiry>0, 要求发送消息的生命周期大于[system]中的核心检测周期TimeV
                msginfo.MsgLen = filename.Length;//消息的长度,若MsgType 为BUF_MSG 类型时，则为消息内容；若MsgType 为FILE_MSG 类型时，则为文件消息的文件名。
                msginfo.MsgType = 1;//文件为1，数据报为0
                msginfo.RemoveFileFlag = 1;//1删除原文件，0不删除
                msginfo.CryptFlag = 0;//0不加密，1加密
                msginfo.PriorNo = PriorNo;//配置的优先及
                msginfo.QueName = QueName;//消息队列名

                int ti = tlqInterface.tlq_putmsg(ref tlqId, ref msginfo, filename, 0);
                // MessageBox.Show(ti.ToString());

                tlqInterface.tlq_logout(ref tlqId);
            }
        }
        /// <summary>
        /// 服务停止事件
        /// </summary>
        protected override void OnStop()
        {

        }


    }
}
